package com.example.restwebservice;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class RestClient {

	private static final String tag = "RestClient";
	private static final String DOMAIN = "http://146.164.16.240:8080";
	

	// "/sciwitter/cadastrar/{nome}/{login}/{senha}"
	public static void cadastrar(String nome, String login, String senha) {
		String response = connect(DOMAIN, "/sciwitter/cadastrar/" + nome.replace(' ', '+') + "/" + login + "/" + senha);
	}

	// "/sciwitter/listarpessoas"
	public static List <Pessoa> listarPessoas() {
		String response = connect(DOMAIN, "/sciwitter/listarpessoas/");
		
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("usuario", Pessoa.class);
		xstream.alias("root", List.class);
		List <Pessoa> pessoas = (List<Pessoa>) xstream.fromXML(response);
		
		return pessoas;
	}

	// "/sciwitter/enviarmensagem/{id}/{mensagem}"
	public static void enviarMensagem(String id_user, String mensagem) {
		connect(DOMAIN, "/sciwitter/enviarmensagem/" + id_user + "/" + mensagem.replace(' ', '+'));
	}

	// "/sciwitter/listarmensagens/{id_user}"
	public static List <String> listarMensagens(String id) {
		String response = connect(DOMAIN, "/sciwitter/listarmensagens/" + id);
		
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("root", List.class);
		xstream.alias("mensagem", String.class);
		List <String> msg = (List<String>) xstream.fromXML(response);

		return msg;
	}
	
		
	
    public static String connect(String domain, String path)
    {
        URI uri = URI.create(domain + path);
 
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(URI.create(domain + path));
		
 
        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            Log.i(tag,response.getStatusLine().toString());
 
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release
 
            if (entity != null) {
 
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= readString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
                
                Log.i(tag, result);
                return result;
            }
 
 
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return "";
    }

    
	private static String readString(InputStream in) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte [] buffer = new byte[1024];
		int len = 0;
		
		try {
			while ((len=in.read(buffer)) > 0) {
				bos.write(buffer, 0, len);
			}
		} catch (IOException e) {
			Log.e(tag, e.getMessage());
		}
		return new String(bos.toByteArray());
	}
}
